import { defineComponent, inject, onMounted, ref, watchEffect } from "vue";

export default defineComponent({
    name: "Cell",
    props: {
        max: {type: Number},
        step: {type: Number},
        type: {type: String},
        name: {type: String},
        value: {type: [Number, String, Object]}
    },
    emits: ['selectTime'],
    setup (props, {emit}) {
        const arr = [];
        for (let i = 0; i < props.max; ) {
            arr.push(i);
            i += props.step || 1;
        }
        const ctx: any = inject('CMTimepickerContext', null);
        const ctx2: any = inject('CMDatepickerContext', null);
        const onClick = (num: number, disabled: boolean) => {
            if (disabled) {
                return;
            }
            ctx && ctx.onSelect(props.type, num, props.name);
            emit('selectTime', props.type, num, props.name);
        };
        const wrap = ref<HTMLDivElement>(null);

        onMounted(() => {
            watchEffect(() => {
                const v = props.value;
                const visible = ctx && ctx.visible.value;
                const visible2 = ctx2 && ctx2.visible.value;
                if (wrap.value && (visible || visible2)) {
                    wrap.value.scrollTop = 26 * (v as number / (props.step || 1));
                }
            });
        });

        return () => <div class="cm-time-picker-cell" ref={wrap}>
            <ul>
                {
                    arr.map((num) => {
                        const disabled = ctx && ctx.disabledTime && ctx.disabledTime(num, props.type);
                        return <li class={{
                            'cm-time-picker-item': true,
                            'cm-time-picker-item-disabled': disabled,
                            'cm-time-picker-item-active': props.value === num,
                        }} onClick={() => onClick(num, disabled)}>
                            {num}
                        </li>;
                    })
                }
            </ul>
        </div>;
    }
});
